package com.iwhalecloud.citybrain.flow.platform.manager.application.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.util.Assert;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @author lilh
 * @date 2019-03-08 09:55
 */
public class WebUtils {

    public static final String APP_ID = "APPID";

    public static final String ORIGIN_EMBED_REQUEST_URL_PARAM = "origin_embed_url";


    /**
     * 添加cookie
     *
     * @param response 响应
     * @param name     变量名
     * @param value    变量值
     */
    public static void addCookie(HttpServletResponse response, String name, String value) {
        try {
            name = URLEncoder.encode(name, "UTF-8");
            value = URLEncoder.encode(value, "UTF-8");
            Cookie cookie = new Cookie(name, value);
            response.addCookie(cookie);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取cookie
     *
     * @param request HttpServletRequest
     * @param name    cookie名称
     * @return 若不存在则返回null
     */
    public static String getCookie(HttpServletRequest request, String name) {
        Assert.notNull(request, "request不能为空");
        Assert.hasText(name, "name不能为空");
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            try {
                name = URLEncoder.encode(name, "UTF-8");
                for (Cookie cookie : cookies) {
                    if (name.equals(cookie.getName())) {
                        return URLDecoder.decode(cookie.getValue(), "UTF-8");
                    }
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 获取appId
     *
     * @param request 请求
     * @return appId
     */
    public static Integer getAppId(HttpServletRequest request) {
        String appId = getCookie(request, APP_ID);
        if (StringUtils.isNotEmpty(appId) && NumberUtils.isCreatable(appId)) {
            return Integer.valueOf(appId);
        }

        return null;
    }

    public static Integer getAppId() {
        return getAppId(getCurrentRequest());
    }

    /**
     * 设置appId
     *
     * @param response 响应
     * @param value    appId的值
     */
    public static void addAppId(HttpServletResponse response, String value) {
        addCookie(response, APP_ID, value);
    }


    /**
     * 获取当前的请求
     *
     * @return 当前的请求
     */
    public static HttpServletRequest getCurrentRequest() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes != null) {
            return requestAttributes.getRequest();
        }
        return null;
    }

    public static Map<String, String> parseQuery(String url) {
        Map<String, String> params = new HashMap<>();
        int index=url.indexOf("?");
        if (index> 0) {
            String paramUrl = url.substring(index+1, url.length() );
            String[] pairs = paramUrl.split("&");
            for (String pair : pairs) {
                int idx = pair.indexOf("=");
                String key = idx > 0 ? pair.substring(0, idx) : pair;
                String value = idx > 0 && pair.length() > idx + 1 ? pair.substring(idx + 1) : null;
                params.put(key, value);
            }
        }
        return params;
    }
}
